import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'



Vue.use(VueRouter)



const router = new VueRouter({
  routes: [
    //路由重定向
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      //只要你访问了/home就重定向到/welcome界面
      redirect: '/welcome',
      children: [
        { path: '/welcome', component: Welcome },
        { path: '/users', component: Users }
      ]
    }
  ]
})
//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  //to 去哪   from 从哪来   next()表示放行
  //next('/login')   强制跳转
  //是登陆页，直接放行
  if (to.path === '/login') return next()
  //获取token  window.sessionStorage.getItem(key)
  const tokenStr = window.sessionStorage.getItem('token')
  //如果字符串不存在，就是没登录，强制滚回登录页去
  if (!tokenStr) return next('/login')
  //如果没有return出去，证明存在，直接放行
  next()


})

export default router
